<?php

namespace App\Services;

use App\Models\Acc;
use App\Models\Acc as AccModel;
use App\Models\User as UserModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class User
{
    protected UserModel $userModel;
    protected AccModel $accModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->accModel = new AccModel();
    }

    public function register(array $data)
    {
        $data['acc_lg_pwd'] = Hash::make($data['acc_lg_pwd']);

        return DB::transaction(function () use ($data) {
            $userData = [
                'user_status' => UserModel::USER_STATUS['normal'],
                'user_reg_fr' => UserModel::USER_REG_FR['app'],
                'user_gender' => UserModel::USER_GENDER['unknown'],
                'user_icon' => $data['acc_user_icon'] ?? '',
                'user_age' => $data['user_age'],
                'user_nick' => $data['acc_user_nick'] ?? $data['acc_lg_name'],// 默认用用户名填充昵称字段
                'user_reg_dt' => date('Y-m-d H:i:s'),
            ];
            $user = UserModel::create($userData);

            $accData = [
                'acc_user_id' => $user['id'],
                'acc_status' => AccModel::ACC_STATUS['normal'],
                'acc_lg_name' => $data['acc_lg_name'],
                'acc_lg_pwd' => $data['acc_lg_pwd'],
                'acc_user_nick' => $data['acc_user_nick'] ?? $data['acc_lg_name'],// 默认用用户名填充昵称字段
                'acc_user_icon' => $data['acc_user_icon'] ?? '',
            ];
            $acc = AccModel::create($accData);

            return $acc->with('user')->find($acc['acc_user_id']);
        });
    }
}
